<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/4
 * Time: 8:22
 */

namespace app\admin\service;


use think\Db;

class RequestService
{

      private static $app_token='';
      private static $app_id='wxdd1f6dcd35660bdb';
      private static $app_secret='e98f5334ad604f1f610492b02686e7f0';
    /*
    const APPID = 'wxdd1f6dcd35660bdb';
    const MCHID = '1486777032';
    const KEY = 's93kasiwnr98zjxnf84kfkx9wpzlmaww';
    const APPSECRET = 'e98f5334ad604f1f610492b02686e7f0';
    */

    private  static $url='https://api.weixin.qq.com/cgi-bin';

    public  static function getAccessToken()
    {
        $date_now=date("Y-m-d H:i:s");
    //          $where['c.start_lesson_time'] = [['>= time', $homework_starttime], ['<= time', $homework_endtime]];
        $access_token_info=Db::name('oauth')->where('expired_time','gt',$date_now)->find();
         if($access_token_info)
         {//有就直接调用
             return $access_token_info['access_token'];
         }
        //获取接口获取
        $path="token?grant_type=client_credential&appid=".self::getAppid()."&secret=".self::getAppToken();
        $res=self::send($path);
        if(!$res)
        {
            return 'error';
        }
        $model_access_token=Db::name('oauth');
        $model_access_token->access_token=$res['access_token'];
        $model_access_token->expired_time=date("Y-m-d H:i:s",$res['expired_time']+time()-200);
        $model_access_token->where(['id'=>1])->update(['']);
    }
    public static  function send($path,$data=[],$method='GET')
    {
        $request_url=self::$url.$path;
         if($method=='GET')
         {
            $res=HttpClient::get($request_url,[]);
         }else{
             //post
             $res=HttpClient::post($request_url,$data);

         }
        $ret=@json_decode($res,true);
        if(!$ret || (isset($ret['errcode'])&& $ret['errcode']))
        {
                return $ret['errmsg'];
        }
    }
    public static function setConfig($appid,$app_token,$app_secret)
    {
        self::$app_id=$appid;
        self::$app_secret=$app_secret;
        self::$app_token=$app_token;

    }
    public function getAppid()
    {
        return self::$app_id;
    }
    public function getAppToken()
    {
        return self::$app_token;

    }
}